package org.zhs.springframework.context.support;

import org.zhs.springframework.BeansException;
import org.zhs.springframework.context.ConfigurableApplicationContext;
import org.zhs.springframework.core.io.DefaultResourceLoader;
import org.zhs.springframework.factory.ConfigurableListableBeanFactory;
import org.zhs.springframework.factory.config.BeanFactoryPostProcessor;
import org.zhs.springframework.factory.config.BeanPostProcessor;

import java.util.Map;

/**
 * 抽象应用上下文
 */
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {


    @Override
    public void refresh() throws BeansException {
        // 1.创建 BeanFactory，并加载 BeanDefinition
        refreshBeanFactory();

        // 2.获取 BeanFactory
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();

        // 3.在将 Bean对象实例化之前，执行 BeanFactoryPostProcessor操作
        invokeBeanFactoryPostProcessors(beanFactory);

        // 4.BeanPostProcessor 需要在将 Bean对象实例化之前注册
        registerBeanPostProcessors(beanFactory);

        // 5.提前实例化单例 Bean 对象
        beanFactory.preInstantiateSingletons();

    }


    protected abstract void refreshBeanFactory() throws BeansException;

    protected abstract ConfigurableListableBeanFactory getBeanFactory();

    private void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory){
        Map<String, BeanFactoryPostProcessor> beanFactoryPostProcessorMap = beanFactory.getBeansOfType(BeanFactoryPostProcessor.class);

        for (BeanFactoryPostProcessor beanFactoryPostProcessor : beanFactoryPostProcessorMap.values()) {
            beanFactoryPostProcessor.postProcessBeanFactory(beanFactory);
        }
    }

    private void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory){
        Map<String, BeanPostProcessor> beanPostProcessorMap = beanFactory.getBeansOfType(BeanPostProcessor.class);

        for (BeanPostProcessor beanPostProcessor : beanPostProcessorMap.values()) {
            beanFactory.addBeanPostProcessor(beanPostProcessor);
        }
    }
}
